# -*- coding: utf-8 -*-
# @Author  : pony.guan
# @Time    : 2021/11/4
# Description: 缓存货架控制权切换

import json
import socket

import requests


def get_local_ip() -> str:
    """
    获取本地ipv4地址
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('8.8.8.8', 80))
        addr, port = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"


def to_switch() -> dict:
    url = "http://ess-master.dev.com/station/changeGroupLock"
    headers = {
        "Content-Type": "application/json"
    }
    ip = get_local_ip()
    station_code = "1-1" if ip == "10.168.33.54" else "1-2"
    data = {
        "stationCode": station_code,
        "groupCode": "group1",  # 固定
        "lockStatus": "ESS"  # 固定
    }

    r = requests.post(url=url, data=json.dumps(data, ensure_ascii=False),  headers=headers)

    if r.json()['code'] == 0:
        return {
            "code": 1000,
            "data": r.json()["data"]
        }
    else:
        return {
            "code": 1001,
            "error": "failed"
        }
